<template>
	<!-- <n-modal :show="" :on-mask-click="onClose" class="base-popup " transform-origin="center"></n-modal> -->
	<transition @enter="onEnter" @leave="onLeave"></transition>
	<div v-if="searchGameStore.visible" class="global-search__wrapper" @keydown.esc="onClose">
		<div @click="onClose" class="global-search__fake-wrapper"></div>
		<div
			class="md:w-[1300px] w-full bg-bg-1 rounded pt-[20px] pb-[20px] pl-[25px] pr-[25px] global-search__container">
			<div
				class="flex items-center rounded-lg border border-border-1 bg-bg-3 w-100 flex-1 text-t-3 mb-[20px] border-[#546371]"
				:class="{ 'search-focus': isFocus }">
				<n-popover
					ref="popoverRef"
					trigger="click"
					placement="bottom"
					:show-arrow="false"
					class="overflow-hidden">
					<template #trigger>
						<div
							class="flex border-r px-[12px] py-[9px] items-center border-[#546371] cursor-pointer"
							@click="typeShow = !typeShow"
							:class="{ 'search-focus': isFocus }">
							<div class="text-t-1 mr-1">{{ $t(selectedType?.title) }}</div>
							<base-icon
								class="text-[16px] duration-300"
								name="down"
								:class="{
									'rotate-180': typeShow
								}"></base-icon>
						</div>
					</template>
					<div
						v-for="(item, index) in typeList"
						:key="index"
						class="flex items-center p-[10px] cursor-pointer hover:bg-bg-3 min-w-[73px]"
						@click="handleSelectType(item)">
						{{ $t(item.title) }}
					</div>
				</n-popover>

				<div class="flex justify-between pl-[14px] pr-[12px] flex-1">
					<base-icon class="text-[20px] flex-shrink-0 pr-[5px]" name="search"></base-icon>
					<input
						v-model="currentSearchWord"
						@keyup="searchWordTyping"
						type="text"
						@focus="isFocus = true"
						@blur="isFocus = false"
						autofocus
						class="flex-1 bg-transparent outline-none text-t-2 placeholder:text-t-2"
						:placeholder="$t('action.searchGame')" />
					<base-icon
						class="text-[20px] flex-shrink-0 pr-[5px] cursor-pointer"
						name="close"
						@click="handleClose()"></base-icon>
				</div>
			</div>

			<div v-if="loading" class="flex items-center w-full justify-center h-[268px]">
				<BaseLoadingCircle />
			</div>
			<!-- <div class="relative loading-wrapper">
					<div class="loading-img__container" v-for=" in 5">
						<base-image src="placeholder" class="loading-img"></base-image>
					</div>
				</div> -->
			<div v-else>
				<div class="mb-4" v-if="searchResult.length > 0">
					<div class="flex justify-between">
						<div>{{ $t('casino.searchResult') }}</div>
						<div class="flex">
							{{ $t('casino.searchFound') }}
							<div class="text-primary mx-[2px]">{{ searchResult.length }}</div>
							{{ $t('casino.searchFoundResult') }}
						</div>
					</div>
					<n-grid
						ref="el"
						:y-gap="isDesktop ? 10 : 16"
						:x-gap="isDesktop ? 12 : 8.5"
						:cols="isDesktop ? 10 : 3">
						<n-gi v-for="(item, index) in searchResult" :key="index" class="app-hover-offset">
							<item-card :item="item" />
						</n-gi>
					</n-grid>
				</div>
				<div class="mb-4" v-else>
					<div class="text-center mt-[20px] mb-[20px] text-t-3">
						<div v-if="currentSearchWord.length > 2 && searchResult.length === 0">
							{{ $t('casino.searchNoResult') }}
						</div>
						<div v-else>{{ $t('casino.minSearchLength') }}</div>
					</div>
					<div class="mb-[16px] text-t-3" v-if="searchHistoryList.length > 0">
						<div class="flex justify-between pb-[10px] search-game_title">
							<div>{{ $t('casino.searchHistory') }}</div>
							<base-icon
								class="text-[20px] flex-shrink-0 cursor-pointer"
								name="clear"
								@click="removeHistorySearchWordAll()"></base-icon>
						</div>
						<div class="flex text-t-2 flex-wrap gap-2">
							<div
								class="bg-bg-3 rounded p-[5px] pr-[10px] pl-[10px] app-bg-react whitespace-nowrap"
								v-for="item in searchHistoryList">
								<span class="mr-[5px]" @click="handleSearchWord(item)">{{ item }}</span>
								<base-icon
									class="text-[12px] flex-shrink-0"
									name="remove"
									@click="removeHistorySearchWord(item)"></base-icon>
							</div>
						</div>
					</div>
					<div class="text-t-3" v-if="recommendList.length > 0">
						<div class="flex justify-between pb-[10px] search-game_title">
							<div>{{ $t('casino.searchRecommend') }}</div>
							<!-- <div>Delete</div> -->
						</div>
						<div class="flex text-t-2">
							<div
								class="bg-bg-3 rounded p-[5px] mr-[5px] pr-[10px] pl-[10px] app-bg-react"
								v-for="(item, index) in recommendList"
								:key="index"
								@click="handleSearchWord(item.keyword)">
								{{ item.keyword as any }}
							</div>
						</div>
					</div>
				</div>
				<game-list type="casino"></game-list>
			</div>
		</div>
	</div>
</template>
<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import { useSearchGameStore } from '@/store'
import { BaseLoadingCircle } from '@/components/base'
import { NPopover, PopoverInst } from 'naive-ui'
import { BaseIcon } from '@/components/base'
import GameList from '@/components/slots/game-list/index.vue'
import { t } from '@/utils'
import {
	globalSearchGame,
	globalSearchRecommend,
	globalSearchHistory,
	globalSearchHistoryDeleteAll,
	globalSearchHistoryDeleteByKeyword
} from '@/api/other.ts'
import { NGi, NGrid } from 'naive-ui'
import { isDesktop } from '@/hooks/useIsPC.ts'
import ItemCard from '@/components/slots/common/item-card.vue'
import gsap from 'gsap'
import { useDialog } from '@/hooks'
import { useAccountStore } from '@/store'
import { useRouter } from 'vue-router'

const dialog = useDialog()
const searchGameStore = useSearchGameStore()
const accountStore = useAccountStore()

const searchHistoryList = ref([])
const typeList = ref([
	{
		id: 'casino',
		title: 'casino.title',
		recomendId: 'CASINO_SEARCH_DISPLAY'
	},
	{
		id: 'sports',
		title: 'app.sports',
		recomendId: 'SPORT_SEARCH_DISPLAY'
	}
])

const selectedType = ref(typeList.value[0])
const typeShow = ref(false)
const currentSearchWord = ref('')
const recommendList = ref(<any[]>[])
const searchResult = ref([])
const loading = ref(false)
const isFocus = ref(true)
const popoverRef = ref<PopoverInst | null>(null)

const router = useRouter()
watch(
	() => accountStore.isLogin,
	() => {
		getSearchHistory()
	}
)
watch(
	() => router.currentRoute.value,
	(currentRoute) => {
		changeCategory(currentRoute.name)
	}
)
onMounted(() => {
	getSearchRecomend()
	getSearchHistory()
})

const onClose = () => {
	resetAll()
	searchGameStore.hide()
}
const removeHistorySearchWord = async (item: any) => {
	await globalSearchHistoryDeleteByKeyword(item)
	getSearchHistory()
}
const removeHistorySearchWordAll = async () => {
	dialog.warning({
		title: t('app.deleteSearchHistoryTitle'),
		content: t('app.deleteSearchHistoryContent'),
		confirmFn: async () => {
			await globalSearchHistoryDeleteAll()
			getSearchHistory()
		}
	})
}
const searchWordTyping = () => {
	getList()
}
const handleSearchWord = (item: any) => {
	currentSearchWord.value = item
	getList()
}
const handleClose = () => {
	if (currentSearchWord.value.length > 2) {
		currentSearchWord.value = ''
		searchResult.value = []
	} else {
		onClose()
	}
}
const getList = async () => {
	if (currentSearchWord.value.length > 2) {
		loading.value = true
		const result = await globalSearchGame({
			keyword: currentSearchWord.value,
			type: selectedType.value.id
		})
		searchResult.value = result.data
		setTimeout(() => {
			loading.value = false
		}, 600)

		getSearchHistory()
	} else {
		searchResult.value = []
	}
}
const handleSelectType = (item: any) => {
	selectedType.value = item
	popoverRef.value?.setShow(false)
}
const resetAll = () => {
	currentSearchWord.value = ''
	searchResult.value = []
	loading.value = false
}
const onEnter = (el: any, done: any) => {
	gsap.from(el, {
		opacity: 0,
		duration: 0.18,
		ease: 'power1.in',
		onComplete: done
	})
}
const onLeave = (el: any, done: any) => {
	gsap.to(el, {
		opacity: 0,
		duration: 0.18,
		ease: 'power1.out',
		onComplete: done
	})
}

const getSearchRecomend = async () => {
	const result = await globalSearchRecommend({
		page: 1,
		pageSize: 24,
		displayLocation: selectedType.value.recomendId
	})
	recommendList.value = result.data
}

const getSearchHistory = async () => {
	const result = await globalSearchHistory()
	searchHistoryList.value = result.data
}
const changeCategory = (item: any) => {
	let selected = typeList.value.find((x) => x.id === item) as any
	if (!selected) {
		selected = typeList.value.find((x) => x.id === 'casino') as any
	}
	handleSelectType(selected)
}
</script>
<style>
.search-focus {
	border-color: var(--color-primary) !important;
}

.loading-img {
	width: 100%;
	height: 100%;
	object-fit: cover;
}
.loading-wrapper {
	display: grid;
	grid-template-columns: repeat(8, 1fr);
	gap: 10px 10px;
}
.loading-img__container {
	background: rgba(174, 184, 214, 0);
	border-radius: 8px;
	aspect-ratio: 1 / 1.5;
	animation: loading-gradient 1.5s linear infinite;
	overflow: hidden;
}
.global-search__container {
	margin-top: 80px;
	z-index: 2;
}
.global-search__wrapper {
	position: fixed;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	align-items: flex-start;
	justify-content: center;
	z-index: 9;
}
.global-search__fake-wrapper {
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	background: rgba(0, 0, 0, 0.5);
	backdrop-filter: blur(6px);
	opacity: 1;
	transition: all 3s;
}
@media (max-width: 768px) {
	.loading-wrapper {
		grid-template-columns: repeat(3, 1fr);
	}
	.global-search__container {
		margin-top: 60px;
		border-radius: 0 !important;
	}
}
</style>
